package io.wongxd.solution.baseView

import android.view.Window
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.google.accompanist.systemuicontroller.rememberSystemUiController

@Composable
fun SetStatusBar(
    window: Window,
    resetStatusBarMs: Long,
    color: Color = Color.Transparent,
    darkIcon: Boolean = false,
    avoidStatusBar: Boolean = false,
    onResetStatusBarMsChange: (Long) -> Unit,
    content: @Composable () -> Unit
) {

    WindowCompat.setDecorFitsSystemWindows(window, false)

    val systemUiController = rememberSystemUiController()
    LaunchedEffect(key1 = resetStatusBarMs, block = {
        systemUiController.setStatusBarColor(color, darkIcons = darkIcon)
    })

    val lifecycle = LocalLifecycleOwner.current.lifecycle
    DisposableEffect(lifecycle) {
        // Make MapView follow the current lifecycle
        val lifecycleObserver = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_RESUME) {
                onResetStatusBarMsChange.invoke(System.currentTimeMillis())
            }
        }
        lifecycle.addObserver(lifecycleObserver)
        onDispose {
            lifecycle.removeObserver(lifecycleObserver)
        }
    }

    if (avoidStatusBar)
        Column {
            Spacer(modifier = Modifier.windowInsetsPadding(WindowInsets.statusBars))

            content()
        } else content()

}